package com.bfxy.disruptor.heigh.chain;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

import com.bfxy.disruptor.common.Disruptor;
import com.bfxy.disruptor.common.EventTranslator;
import com.bfxy.disruptor.quickstart.OrderEvent;

//import com.lmax.disruptor.EventTranslator;
//import com.lmax.disruptor.dsl.Disruptor;

public class TradePushlisher implements Runnable {

	private Disruptor<Trade> disruptor;
	private CountDownLatch latch;
	
	private static int PUBLISH_COUNT = 1;
	
	public TradePushlisher(CountDownLatch latch, Disruptor<Trade> disruptor) {
		this.disruptor = disruptor;
		this.latch = latch;
	}

	public void run() {
		TradeEventTranslator eventTranslator = new TradeEventTranslator();
		for(int i =0; i < PUBLISH_COUNT; i ++){
			//新的提交任务的方式
			disruptor.publishEvent(eventTranslator);	
			/*之前是：long sequence = ringBuffer.next();	//0	
			try {
				OrderEvent event = ringBuffer.get(sequence);
				event.setValue(data.getLong(0));//getLong(0)取哪个位置的数据		
			} finally {
				ringBuffer.publish(sequence);			
			}
			现在是：继承EventTranslator，重写translateTo方法，*/
		}
		latch.countDown();
	}
}

class TradeEventTranslator implements EventTranslator<Trade> {

	private Random random = new Random();

	public void translateTo(Trade event, long sequence) {//sequence就是插入的位置
		this.generateTrade(event);
	}

	private void generateTrade(Trade event) {
		event.setPrice(random.nextDouble() * 9999);
	}
}